//
//  CustomShowPhotoListViewController.m
//  ExcellentHome
//
//  Created by Andy on 15/11/12.
//  Copyright © 2015年 陈区. All rights reserved.
//

#import "CustomShowPhotoListViewController.h"

#if __has_include(<Commom/SEGLayoutMacro.h>)
#import <Commom/SEGLayoutMacro.h>
#else
#import "SEGLayoutMacro.h"
#endif

#import <Masonry/Masonry.h>

#if __has_include(<Commom/SEGColorManager.h>)
#import <Commom/SEGColorManager.h>
#else
#import "SEGColorManager.h"
#endif

#import "UIViewController+SEGNaviAdd.h"

@interface CustomShowPhotoListViewController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate>
/**
 选中的图片key数组 按照选择顺序排列
 */
@property (nonatomic, strong)NSMutableArray *selectedImageKeyArray;
@property (nonatomic, strong)ALAssetsLibrary *assetsLibrary;
@end

@implementation CustomShowPhotoListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor lightGrayColor];
    
    screenWidth = CGRectGetWidth(self.view.bounds)/linePhotoNumber;
    
    photoArray = [[NSMutableArray alloc] init];
    groupArray = [[NSMutableArray alloc] init];
    selDict = [[NSMutableDictionary alloc] init];
    _selectedImageKeyArray = [[NSMutableArray alloc] init];
    
    tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    [self.view addSubview:tableView];
    tableView.contentInset = UIEdgeInsetsMake(kNavigationBarAndStatusBarHeight, 0, 0, 0);
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.tableFooterView = [[UIView alloc] init];
    
    //工具条
    UIView *barView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), kNavigationBarAndStatusBarHeight)];
    barView.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.9];
    [self.view addSubview:barView];
    
    [barView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(self.view);
        make.height.mas_equalTo(kNavigationBarAndStatusBarHeight);
    }];
    
    //分隔线
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0,CGRectGetHeight(barView.bounds)-0.5, CGRectGetWidth(barView.bounds), 0.5)];
    lineView.backgroundColor = [UIColor grayColor];
    [barView addSubview:lineView];
    
    //标题
    titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, kStatusbarHeight, CGRectGetWidth(barView.bounds), CGRectGetHeight(barView.bounds) - kStatusbarHeight)];
    [titleLabel setText:@"总共0张  当前选择了0张"];
    [titleLabel setTextAlignment:NSTextAlignmentCenter];
    [barView addSubview:titleLabel];
    
    CGFloat titleLabelHeight = LYIsiPhoneX() ? kNavigationBarAndStatusBarHeight - LYSafeAreaBottom() : kNavigationBarAndStatusBarHeight - 20;
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.equalTo(barView);
        make.height.mas_equalTo(titleLabelHeight);
    }];
    
    //取消
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    cancelBtn.frame = CGRectMake(CGRectGetWidth(barView.bounds)-60, kStatusbarHeight, 60, 44);
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    [cancelBtn setTitleColor:kColor_T forState:UIControlStateNormal];
    [cancelBtn.titleLabel setFont:[UIFont systemFontOfSize:14]];
    [cancelBtn addTarget:self action:@selector(cancelAction:) forControlEvents:UIControlEventTouchUpInside];
    [barView addSubview:cancelBtn];
    
    [cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(titleLabel);
        make.right.equalTo(barView);
        make.width.mas_equalTo(60);
        make.height.mas_equalTo(44);
    }];
    
    [self.assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
        [group setAssetsFilter:[ALAssetsFilter allPhotos]];
        if (stop) {
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
                [group enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
                    if (result) {
                        if ([[group valueForProperty:ALAssetsGroupPropertyType] intValue]==ALAssetsGroupSavedPhotos) {
                            [photoArray insertObject:result atIndex:0];
                        } else {
                            [photoArray addObject:result];
                        }
                    }
                }];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [titleLabel setText:[NSString stringWithFormat:@"总共%d张  当前选择了0张",(int)[photoArray count]]];
                    [tableView reloadData];
                });
            });
        } else {
            if (group) {
                [groupArray addObject:group];
            }
        }
    } failureBlock:^(NSError *error) {
    }];
    
    //完成
    downView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetHeight(self.view.bounds)-40, CGRectGetWidth(self.view.bounds), 40)];
    [downView setHidden:YES];
    downView.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:1];
    [self.view addSubview:downView];
    
    [downView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.height.mas_equalTo(40 + LYSafeAreaBottom());
    }];
    
    UIButton *finishedBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    finishedBtn.frame = CGRectMake(CGRectGetWidth(downView.bounds)-60, (CGRectGetHeight(downView.bounds)-40)/2, 60, 40);
    [finishedBtn setTitle:@"完成" forState:UIControlStateNormal];
    [finishedBtn setTitleColor:kColor_T forState:UIControlStateNormal];
    [finishedBtn.titleLabel setFont:[UIFont systemFontOfSize:13]];
    [finishedBtn addTarget:self action:@selector(finishedAction:) forControlEvents:UIControlEventTouchUpInside];
    [downView addSubview:finishedBtn];
    
    //选择数
    UIView *selectView = [[UIView alloc] initWithFrame:CGRectMake(CGRectGetWidth(downView.bounds)-70, (CGRectGetHeight(downView.bounds)-17)/2, 17, 17)];
    selectView.backgroundColor = kColor_T;
    selectView.layer.cornerRadius = 8;
    [selectView.layer setMasksToBounds:YES];
    [downView addSubview:selectView];
    
    selectLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 17, 17)];
    [selectLabel setText:@"1"];
    [selectLabel setFont:[UIFont systemFontOfSize:13]];
    [selectLabel setTextColor:[UIColor whiteColor]];
    [selectLabel setTextAlignment:NSTextAlignmentCenter];
    [selectView addSubview:selectLabel];
    
    
    [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.equalTo(self.view);
        make.bottom.equalTo(downView.mas_top).offset(40 + LYSafeAreaBottom());
    }];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:YES];
    if (_photoMax<=0)
    {
        _photoMax = selectPhotoMax;
    }
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:YES];
}

//打开相册或相机
- (void)showPhotoStyle:(NSInteger)style {
    if (_photoType>1)
    {
        [self showCamreaView];
    }
    else
    {
        [self showAlbumView];
    }
}

//创建相册选择
- (void)showAlbumView {
    
}

//创建相机选择
- (void)showCamreaView {
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    //判断是否有相机
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]){
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        //设置拍照后的图片可被编辑
        picker.allowsEditing = YES;
        //资源类型为照相机
        picker.sourceType = sourceType;
        [self.navigationController pushViewController:picker animated:YES];
    }else {
    }
}

//取消
- (void)cancelAction:(UIButton *)sender {
    [self.fundelegate ShowPhotoListViewCancelAction:self];
}

//选择
- (void)finishedAction:(UIButton*) sender {
    
    NSMutableArray *tempArray = [[NSMutableArray alloc] init];
    
    [self.selectedImageKeyArray enumerateObjectsUsingBlock:^(NSString *key, NSUInteger idx, BOOL * _Nonnull stop) {
        NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
        
        CustomButtonView *abtn = [selDict objectForKey:key];
        UIImageView *imageView = [abtn.subviews objectAtIndex:0];
        UIImage *image = [imageView image];
        
        ALAsset *asset = [abtn tempData];
        //获取照片拍摄日期
        NSDate *date = (NSDate *)[asset valueForProperty:ALAssetPropertyDate];
        [params setObject:image forKey:key];
        [params setObject:[UIImage imageWithCGImage:[[asset defaultRepresentation] fullScreenImage]] forKey:[NSString stringWithFormat:@"big%@",key]];
        [params setObject: date forKey:@"creatDate"];
        
        [tempArray addObject:params];
    }];
    
    if (self.fundelegate && [self.fundelegate respondsToSelector:@selector(ShowPhotoListViewFinishedAction:actionView:)]) {
        [self.fundelegate ShowPhotoListViewFinishedAction:tempArray actionView:self];
    }
}

- (void)reloadData {
    [tableView reloadData];
}


#pragma mark - <UITableViewDataSource & UITableViewDelegate> method

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)_tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *cellStr = @"cell";
    UITableViewCell *cell = [_tableView dequeueReusableCellWithIdentifier:cellStr];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellStr];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    } else {
        for (UIView *aview in cell.contentView.subviews) {
            [aview removeFromSuperview];
        }
    }
    
    for (int i=0; i<linePhotoNumber; i++) {
        if (i+indexPath.row*linePhotoNumber<[photoArray count]) {
            ALAsset *asset = [photoArray objectAtIndex:i+indexPath.row*linePhotoNumber];
            
            CustomButtonView *abtn = [[CustomButtonView alloc] init];
            [abtn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
            abtn.frame = CGRectMake(i*screenWidth,0, screenWidth, screenWidth);
            abtn.tag = 100+(i+indexPath.row*linePhotoNumber);
            [cell.contentView addSubview:abtn];
            abtn.tempData = asset;
            
            UIImage *image = [UIImage imageWithCGImage:[asset aspectRatioThumbnail]];
            UIImageView *aimageView = [[UIImageView alloc] initWithFrame:CGRectMake(4,4, CGRectGetWidth(abtn.bounds)-8, CGRectGetHeight(abtn.bounds)-8)];
            aimageView.contentMode = UIViewContentModeScaleAspectFill;
            [aimageView.layer setMasksToBounds:YES];
            [abtn addSubview:aimageView];
            [aimageView setImage:image];
            
            for (NSString *key in [selDict allKeys]) {
                if ([key isEqualToString:[NSString stringWithFormat:@"%d",(int)abtn.tag]]) {
                    [aimageView addSubview:[self addFlagView:CGRectMake(0, 0, CGRectGetWidth(aimageView.bounds), CGRectGetHeight(aimageView.bounds))]];
                }
            }
        }
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)_tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return screenWidth;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [photoArray count]%linePhotoNumber==0?[photoArray count]/linePhotoNumber:[photoArray count]/linePhotoNumber+1;
}

- (void)btnAction:(CustomButtonView *)sender {
    UIImageView *aImageView = [sender.subviews objectAtIndex:0];
    NSString *senderKey = [NSString stringWithFormat:@"%d",(int)sender.tag];
    
    BOOL isSelected = YES;
    
    //如果已经选中，取消当前选中状态
    for (NSString *keyAll in [selDict allKeys])  {
        if ([keyAll isEqualToString:senderKey]) {
            UIView *aview = [aImageView.subviews objectAtIndex:0];
            [aview removeFromSuperview];
            [selDict setValue:nil forKey:senderKey];
            
            //从选中图片key数组中删除取消的图片
            if ([self.selectedImageKeyArray containsObject:senderKey]) {
                [self.selectedImageKeyArray removeObject:senderKey];
            }
            
            isSelected = NO;
        }
    }
    
    if (isSelected) {
        //判断是否选择规定的个数
        if ([selDict count]>=_photoMax) {
            return;
        }
        
        [aImageView addSubview:[self addFlagView:CGRectMake(0, 0, CGRectGetWidth(aImageView.bounds), CGRectGetHeight(aImageView.bounds))]];
        
        [selDict setObject:sender forKey:senderKey];
        
        //将选中的图片放入选中图片key数组中 保持和点击顺序相同
        [self.selectedImageKeyArray addObject:senderKey];
    }
    
    [titleLabel setText:[NSString stringWithFormat:@"总共%d张  当前选择了%d张",(int)[photoArray count],(int)[selDict count]]];
    [selectLabel setText:[NSString stringWithFormat:@"%d",(int)[selDict count]]];
    
    //判断是否有选择
    if ([selDict count] > 0) {
        [downView setHidden:NO];
        [tableView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(downView.mas_top);
        }];
    } else {
        [downView setHidden:YES];
        [tableView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(downView.mas_top).offset(40 + LYSafeAreaBottom());
        }];
    }
}



//添加标记
- (UIView *)addFlagView:(CGRect)frame {
    UIView *selBgView = [[UIView alloc] initWithFrame:frame];
    selBgView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
    
    //加载图标
    UIImage *iconImage = [UIImage imageWithContentsOfFile:SEGPicName(@"cart_radio_pre")];
    UIImageView *iconView = [[UIImageView alloc] initWithFrame:CGRectMake(CGRectGetWidth(selBgView.bounds)-iconImage.size.width-5, 5, iconImage.size.width, iconImage.size.height)];
    [iconView setImage:iconImage];
    [selBgView addSubview:iconView];
    
    return selBgView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -
#pragma mark 相机回调
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    
    //    UIImage *image = [info valueForKey:@""];
    //关闭相册界面
    [picker dismissViewControllerAnimated:YES completion:^{
        //
    }];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [self dismissViewControllerAnimated:YES completion:^{
    }];
}


-(ALAssetsLibrary *)assetsLibrary{
    if (!_assetsLibrary) {
        _assetsLibrary = [[ALAssetsLibrary alloc] init];
    }
    return _assetsLibrary;
}
@end
